import styles from 'styles/Home.module.scss'
import { getPosts } from 'lib/post';
import Link from 'next/link';
import { PostMeta } from 'interface/post'
import dayjs from 'dayjs'
import { NextPageWithLayout } from './_app';
import Layout from 'components/layout/index'
import Intro from 'components/intro'

const Home: NextPageWithLayout<{ posts: PostMeta[] }> = (props) => {

  const { posts } = props
  return (
    <div className={styles.container}>
      <Intro />
      <main className={styles.main}>
        {posts && (
          <>
            {posts.map((item, index) => (
              <div className={styles['post-item']} key={item.id + index}>
                <Link href={`/${item.id}`}>
                  <a className={styles.link}>{item.title}</a>
                </Link>
                <span className={styles.time}>{item.date}</span>
              </div>
            ))}
            <p className={styles.omit}>...</p>
          </>
        )}
      </main>
    </div>
  )
}

Home.getLayout = Layout

export default Home

export const getStaticProps = async (context: any) => {
  const posts = await getPosts()
  const result = posts.map((item) => {
    return {
      ...item,
      date: item.date ? dayjs(item.date).format('YYYY-MM-DD') : '-'
    }
  }).splice(0, 20)
  return {
    props: {
      posts: JSON.parse(JSON.stringify(result || null))
    }
  };
};